<template>
  <div class="sales-report">
    <!-- 页面标题和操作栏 -->
    <div class="report-header">
      <h2>销售报表</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-select v-model="timeType" placeholder="时间类型" style="width: 120px; margin-left: 10px;">
          <el-option label="日" value="day" />
          <el-option label="周" value="week" />
          <el-option label="月" value="month" />
          <el-option label="季" value="quarter" />
          <el-option label="年" value="year" />
        </el-select>
        <el-button type="primary" @click="refreshData" style="margin-left: 10px;">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-dropdown style="margin-left: 10px;">
          <el-button type="success">
            导出 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="exportExcel">导出Excel</el-dropdown-item>
              <el-dropdown-item @click="exportPDF">导出PDF</el-dropdown-item>
              <el-dropdown-item @click="exportImage">导出图片</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button @click="printReport" style="margin-left: 10px;">
          <el-icon><Printer /></el-icon>
          打印
        </el-button>
      </div>
    </div>

    <!-- 关键指标卡片 -->
    <el-row :gutter="20" class="metrics-cards">
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(totalSales) }}</div>
            <div class="metric-label">总销售额</div>
            <div class="metric-change positive">+12.5%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">{{ formatNumber(totalOrders) }}</div>
            <div class="metric-label">订单数量</div>
            <div class="metric-change positive">+8.3%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">¥{{ formatNumber(avgOrderValue) }}</div>
            <div class="metric-label">平均订单价值</div>
            <div class="metric-change negative">-2.1%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-content">
            <div class="metric-value">{{ customerCount }}</div>
            <div class="metric-label">客户数量</div>
            <div class="metric-change positive">+15.7%</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="charts-section">
      <!-- 销售趋势图 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>销售趋势</span>
          </template>
          <div ref="salesTrendChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 销售分布饼图 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>销售分布</span>
          </template>
          <div ref="salesDistributionChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="charts-section">
      <!-- 产品销售排行 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>产品销售排行</span>
          </template>
          <div ref="productRankingChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
      
      <!-- 客户销售排行 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>客户销售排行</span>
          </template>
          <div ref="customerRankingChart" style="height: 300px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细数据表格 -->
    <el-card class="data-table-card">
      <template #header>
        <span>销售明细</span>
      </template>
      <el-table :data="salesDetailData" stripe style="width: 100%">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="orderNo" label="订单号" width="150" />
        <el-table-column prop="customer" label="客户" width="150" />
        <el-table-column prop="product" label="产品" width="200" />
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="unitPrice" label="单价" width="120">
          <template #default="scope">
            ¥{{ scope.row.unitPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="总金额" width="120">
          <template #default="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="salesperson" label="销售员" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalRecords"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, ArrowDown, Printer } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const dateRange = ref<[string, string]>(['2024-01-01', '2024-12-31'])
const timeType = ref('month')
const currentPage = ref(1)
const pageSize = ref(20)
const totalRecords = ref(100)

// 关键指标
const totalSales = ref(2580000)
const totalOrders = ref(1250)
const avgOrderValue = ref(2064)
const customerCount = ref(380)

// 图表引用
const salesTrendChart = ref()
const salesDistributionChart = ref()
const productRankingChart = ref()
const customerRankingChart = ref()

// 销售明细数据
const salesDetailData = ref([
  {
    date: '2024-01-15',
    orderNo: 'SO202401001',
    customer: '北京科技有限公司',
    product: '笔记本电脑',
    quantity: 10,
    unitPrice: 5500,
    totalAmount: 55000,
    salesperson: '张三',
    status: '已完成'
  },
  {
    date: '2024-01-16',
    orderNo: 'SO202401002',
    customer: '上海贸易公司',
    product: '办公桌椅',
    quantity: 20,
    unitPrice: 800,
    totalAmount: 16000,
    salesperson: '李四',
    status: '进行中'
  },
  {
    date: '2024-01-17',
    orderNo: 'SO202401003',
    customer: '广州制造企业',
    product: '打印机',
    quantity: 5,
    unitPrice: 2200,
    totalAmount: 11000,
    salesperson: '王五',
    status: '已完成'
  }
])

// 方法
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '已完成': 'success',
    '进行中': 'warning',
    '已取消': 'danger'
  }
  return statusMap[status] || 'info'
}

const handleDateChange = () => {
  refreshData()
}

const refreshData = () => {
  ElMessage.success('数据已刷新')
  // 这里可以调用API刷新数据
}

const exportExcel = () => {
  ElMessage.success('Excel导出功能开发中')
}

const exportPDF = () => {
  ElMessage.success('PDF导出功能开发中')
}

const exportImage = () => {
  ElMessage.success('图片导出功能开发中')
}

const printReport = () => {
  window.print()
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  // 重新加载数据
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  // 重新加载数据
}

// 初始化图表
const initCharts = () => {
  // 销售趋势图
  const salesTrend = echarts.init(salesTrendChart.value)
  salesTrend.setOption({
    title: {
      text: '月度销售趋势',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: ¥{c}万'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '销售额(万元)'
    },
    series: [{
      data: [120, 132, 101, 134, 90, 230, 210, 182, 191, 234, 290, 330],
      type: 'line',
      smooth: true,
      itemStyle: { color: '#409EFF' }
    }]
  })

  // 销售分布饼图
  const salesDistribution = echarts.init(salesDistributionChart.value)
  salesDistribution.setOption({
    title: {
      text: '产品类别销售分布',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [{
      name: '销售分布',
      type: 'pie',
      radius: '60%',
      data: [
        { value: 335, name: '电子产品' },
        { value: 310, name: '办公用品' },
        { value: 234, name: '家具用品' },
        { value: 135, name: '其他' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  })

  // 产品销售排行
  const productRanking = echarts.init(productRankingChart.value)
  productRanking.setOption({
    title: {
      text: '产品销售排行TOP10',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: ['产品J', '产品I', '产品H', '产品G', '产品F', '产品E', '产品D', '产品C', '产品B', '产品A']
    },
    series: [{
      type: 'bar',
      data: [50, 65, 78, 89, 95, 112, 125, 138, 156, 180],
      itemStyle: { color: '#67C23A' }
    }]
  })

  // 客户销售排行
  const customerRanking = echarts.init(customerRankingChart.value)
  customerRanking.setOption({
    title: {
      text: '客户销售排行TOP10',
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: ['客户J', '客户I', '客户H', '客户G', '客户F', '客户E', '客户D', '客户C', '客户B', '客户A']
    },
    series: [{
      type: 'bar',
      data: [45, 58, 72, 85, 92, 108, 120, 135, 148, 165],
      itemStyle: { color: '#E6A23C' }
    }]
  })
}

onMounted(() => {
  nextTick(() => {
    initCharts()
  })
})
</script>

<style scoped>
.sales-report {
  padding: 20px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.report-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.metrics-cards {
  margin-bottom: 20px;
}

.metric-card {
  text-align: center;
}

.metric-content {
  padding: 10px;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 8px;
}

.metric-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.metric-change {
  font-size: 12px;
  font-weight: bold;
}

.metric-change.positive {
  color: #67C23A;
}

.metric-change.negative {
  color: #F56C6C;
}

.charts-section {
  margin-bottom: 20px;
}

.data-table-card {
  margin-top: 20px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .report-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
    flex-wrap: wrap;
  }
  
  .metrics-cards .el-col {
    margin-bottom: 10px;
  }
}
</style>